<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
    >


<!--      <el-form-item :label="t('formData.factoryCode')" prop="factoryCode">
        <el-select v-model="formData.factoryCode" :placeholder="t('formData.factoryCodeInfo')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FACTORY_CODE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>-->

      <el-form-item :label="t('searchbar.type')" prop="bdType">
        <el-select v-model="formData.bdType" :placeholder="t('searchbar.typeInfo')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.YQ_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

<!--      <el-form-item :label="t('searchbar.model')" prop="bdMode">
        <el-select v-model="formData.bdMode" :placeholder="t('searchbar.modelInfo')" v-if="getSelectOption">
          <el-option
            v-for="dict in getSelectOption"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>-->



      <el-form-item :label="t('searchbar.model')" prop="bdMode">
        <el-select
          v-model="formData.bdMode"
          filterable
          :placeholder="t('searchbar.modelInfo')"
          style="width: 1000px"
          clearable
          :remote-method="remoteMethod"
          :loading="stuAllLoading"
          :filter-method="handleChange"
        >
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.type"
            :value="item.id"
            @click="addForm(item)"
          >
            <span style="float: left"> {{ item.mode }}    ({{ t('searchbar.deviceModeCode') }}:{{ item.deviceModeCode }})</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="t('searchbar.deviceModeCode')" prop="deviceModeCode" v-if="formData.bdMode">
        <el-input v-model="formData.deviceModeCode"  disabled/>
      </el-form-item>




<!--      <el-form-item :label="t('searchbar.model')" prop="bdMode">
        <el-select
          v-model="formData.bdMode"
          filterable
          remote
          reserve-keyword
          :placeholder="t('searchbar.modelInfo')"
          clearable
          :remote-method="modeMethod"
          :loading="AllLoading"
          @keyup.enter="handleChange"
        >
          <el-option
            v-for="item in modeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            @click= "addForm(item)"
          >
            <span style="float: left">仪器型号：{{ item.label }}</span>
          </el-option>
        </el-select>
      </el-form-item>-->



<!--      <el-form-item :label="t('formData.wellId')" prop="wellId" v-if=" formData.wellName != null">
        <el-input v-model="formData.wellId" disabled/>
      </el-form-item>-->

<!--      <el-form-item :label="t('formData.wellName')" prop="wellName">
        <el-select
          v-model="formData.wellName"
          filterable
          :placeholder="t('formData.wellNameInfo')"
          clearable
          :remote-method="remoteMethod"
          :loading="stuAllLoading"
          :filter-method="handleChange"
        >
          <el-option
            v-for="item in siteList"
            :key="item.id"
            :label="item.wellName"
            :value="item.id"
            @click="addForm(item)"
          >
            <span style="float: left"> &lt;!&ndash;{{ t('formData.wellId') }}：{{ item.wellId }}- &ndash;&gt;{{ t('formData.wellName') }}：{{ item.wellName }} </span>
          </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item :label="t('formItems.protocol')" prop="protocol">
        <el-select v-model="formData.protocol" :placeholder="t('formItems.placeholderProtocol')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.XY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('formItems.port')" prop="port" v-if="(formData.protocol == 1 || formData.protocol == 3)">
        <el-input v-model="formData.port" :placeholder="t('formItems.placeholderPort')" />
      </el-form-item>
      <el-form-item :label="t('formItems.ipAddress')" prop="ip" v-if="formData.protocol == 2">
        <el-input v-model="formData.ip" :placeholder="t('formItems.placeholderIp')" />
      </el-form-item>

      <el-form-item :label="t('formData.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="4"
          :placeholder="t('formData.remarkInfo')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('action.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('action.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceApi, DeviceVO } from '@/api/base/device'
import { DeviceBaseApi, DeviceBaseVO } from '@/api/base/devicebase'
import { SiteApi, SiteVO } from '@/api/base/site'

/** 仪器设备 表单 */
defineOptions({ name: 'DeviceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗


const stuAllLoading = ref(false)


const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceSiteCode: undefined,
  deviceModeCode: undefined,
  name: undefined,
  bdType: undefined,
  bdMode: undefined,
  sceneId: undefined,
  factoryCode: undefined,
  remark: undefined,
  state: undefined,
  protocol: undefined,
  port: undefined,
  ip: undefined,
  /*modes:undefined,*/
})
const formRules = reactive({
  name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.getDevice(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceVO
    if (formType.value === 'create') {
      await DeviceApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceSiteCode: undefined,
    deviceModeCode: undefined,
    name: undefined,
    bdType: undefined,
    bdMode: undefined,
    sceneId: undefined,
    factoryCode: undefined,
    remark: undefined,
    state: undefined,
    protocol: undefined,
    port: undefined,
    ip: undefined,
  }
  formRef.value?.resetFields()
}
/*/!*-------------------设备与型号关联部分----------------------*!/
// 计算属性，根据 formData.device 返回相应的选项列表
const getSelectOption = computed(() => {
  const dictTypes = {
    A: DICT_TYPE.A,
    B: DICT_TYPE.B,
    C: DICT_TYPE.C,
    D: DICT_TYPE.D,
    E: DICT_TYPE.E,
    F: DICT_TYPE.F,
    G: DICT_TYPE.G,
    H: DICT_TYPE.H
  };
  return getStrDictOptions(dictTypes[formData.value.bdType]);
});
/!*---------------------------------------------------------*!/*/




/*---------------------------获取仪器型号清单信息------------------------------*/
const deviceList = ref<DeviceBaseVO[]>([])

const deviceParams = reactive({
  bdType: undefined,
  bdMode: undefined,
})
const remoteMethod = async (query) => {
  stuAllLoading.value = true
  deviceList.value = []
  stuAllLoading.value = false


  deviceParams.bdType = formData.value.bdType
  deviceParams.bdMode = query

  deviceList.value = await DeviceBaseApi.getDeviceList(deviceParams)
}

const handleChange = async (query) => {
  deviceList.value=[]

  deviceParams.bdType = formData.value.bdType
  deviceParams.bdMode = query
  deviceList.value = await DeviceBaseApi.getDeviceList(deviceParams)
}

const addForm = (item) => {
  formData.value.bdMode = item.mode
  formData.value.deviceModeCode = item.deviceModeCode
  formData.value.protocol = item.protocol

}


/*/!*---------------------------获取现场信息------------------------------*!/
const siteList = ref<SiteVO[]>([])
const remoteMethod = async (query) => {
  stuAllLoading.value = true
  siteList.value = []
  stuAllLoading.value = false
  siteList.value = await SiteApi.getSiteList(query)
}

const siteName = ref('')

const handleChange = async (query) => {
  siteList.value=[]
  siteList.value = await SiteApi.getSiteList(query)
  // siteName.value = siteList.value[1].wellName
}

const addForm = (item) => {
  formData.value.code = item.code
  formData.value.bdMode = item.mode
}*/



/*/!*---------------------------获取仪器型号------------------------------*!/
const AllLoading = ref(false)
const modeList = ref<DeviceVO[]>([])
const modeMethod = async (query) => {
  AllLoading.value = true
  modeList.value = []
  AllLoading.value = false
  const data =  await DeviceApi.getModeList(query)
  modeList.value = data
}
const modeHandleChange = async (item) => {
  siteListvalue.value = await SiteApi.getSiteList(query)
  bdMode.value = siteListvalue.value[0].mode
}*/


</script>
